export default class DBPool {
    constructor(config) {
        this.mysql = require("mysql2");
        this.config = config
        //1.创建mysql连接对象
        this.pool = this.mysql.createPool(this.config);
    }
    private mysql;
    private config;
    public pool;
    query(sql, params, callBack) {
        //2.打开
        this.pool.getConnection((err, connection) => {
            if (err) {
                console.log("数据库连接失败");
                throw err;
            }
            //3.执行sql查询
            connection.query(sql, params, (err, results, fields) => {
                //4.释放连接
                connection.release();
                // connection.destroy();//销毁链接
                if (err) {
                    console.log("数据库操作失败");
                    throw err;
                }
                callBack && callBack({ results, fields });
            });
        });
    }

    queryAsync(sql, params) {
        const self = this;
        return new Promise((resolve, reject) => {
            this.pool.getConnection((err, connection) => {
                if (err) {
                    console.log("数据库连接失败");
                    reject(err);
                    return;
                }
                connection.query(sql, params, (err, results, fields) => {
                    connection.release();
                    // connection.destroy();
                    if (err) {
                        console.log("数据库操作失败");
                        reject(err);
                        return;
                    }
                    resolve({
                        results,
                        fields,
                    });
                });
            });
        });
    }
    connectAsync(sql, params){
        const self = this;
        return new Promise((resolve, reject) => {
            this.pool.getConnection((err, connection) => {
                if (err) {
                    console.log("数据库连接失败");
                    reject(err);
                    return;
                }
                connection.query(sql, params, (err, results, fields) => {
                    connection.release();
                    // connection.destroy();
                    if (err) {
                        console.log("数据库操作失败");
                        reject(err);
                        return;
                    }
                    resolve('数据连接成功')
                });
            });
        });
    }
}